package com.itgaohe.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itgaohe.common.context.UserContext;
import com.itgaohe.dto.UserDTO;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 *  MetaObjectHandler 实现自动填充字段
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // 插入时自动填充 createTime、updateTime（为当前时间）
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

        // 插入时自动填充 createBy、updateBy（从当前用户上下文获取）
        UserDTO user = UserContext.getUser();
        this.strictInsertFill(metaObject, "createBy", Long.class, user.getId());
        this.strictInsertFill(metaObject, "updateBy", Long.class, user.getId());
    }
    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新时自动填充 updateTime（为当前时间）
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

        // 更新时自动填充 updateBy（从当前用户上下文获取）
        UserDTO user = UserContext.getUser();
        this.strictUpdateFill(metaObject, "updateBy", Long.class, user.getId());
    }

}